package cn.ewan.cloud.tenant.data.router.service.interceptor;

import cn.ewan.cloud.tenant.data.router.core.business.context.TenantContext;
import cn.ewan.cloud.tenant.data.router.core.common.constants.TenantConstants;
import cn.ewan.cloud.tenant.data.router.core.common.util.TenantLog;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lgh
 * @date 2022/12/15 23:13:25
 */
public class HttpTenantInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        String tenant = request.getHeader(TenantConstants.TENANT_TAG);
        TenantContext.setTenant(tenant);
        TenantLog.log("HttpTenantInterceptor preHandle, uri=" + requestURI);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TenantContext.removeTenant();
        String requestURI = request.getRequestURI();
        TenantLog.log("HttpTenantInterceptor afterCompletion, uri=" + requestURI);
    }
}
